﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;

namespace System
{
    /// <summary>
    /// Exception类型扩展
    /// </summary>
    [DebuggerStepThrough]
    public static class ExceptionExtension
    {
        /// <summary>
        /// DbEntityValidationResult转换平面文字
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string DbEntityValidationResultToString(this DbEntityValidationException e)
        {
            return e.EntityValidationErrors
                    .Select(dbEntityValidationResult => dbEntityValidationResult.DbValidationErrorsToString(dbEntityValidationResult.ValidationErrors))
                    .Aggregate(string.Empty, (current, next) => $"{current}{Environment.NewLine}{next}");
        }
        /// <summary>
        /// DbEntityValidationResult转换平面文字
        /// </summary>
        /// <param name="dbEntityValidationResult"></param>
        /// <param name="dbValidationErrors"></param>
        /// <returns></returns>
        public static string DbValidationErrorsToString(this DbEntityValidationResult dbEntityValidationResult, IEnumerable<DbValidationError> dbValidationErrors)
        {
            var entityName = string.Format("[{0}]", dbEntityValidationResult.Entry.Entity.GetType().Name);
            const string indentation = "\t - ";
            var aggregatedValidationErrorMessages = dbValidationErrors.Select(error =>
                    $"[{error.PropertyName} - {error.ErrorMessage}]")
                                                   .Aggregate(string.Empty, (current, validationErrorMessage) => current + (Environment.NewLine + indentation + validationErrorMessage));
            return $"{entityName}{aggregatedValidationErrorMessages}";
        }
    }
}